"""
密码设置对话框 - 允许用户更改付费区密码
"""

from PySide2.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                               QLineEdit, QPushButton, QMessageBox, QFrame,
                               QGridLayout, QWidget, QLayout)
from PySide2.QtCore import Qt, QTimer
from PySide2.QtGui import QFont


class PasswordSettingsDialog(QDialog):
    """密码设置对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("密码设置")
        self.setFixedSize(520, 450)  # 增加高度
        self.setModal(True)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)

        # 设置透明背景
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setup_ui()

    
    def setup_ui(self):
        """设置UI"""
        # 主布局 - 使用容器widget来承载内容
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(15)
        self.main_layout.setContentsMargins(25, 25, 25, 25)

        # 应用毛玻璃效果
        self.apply_glassmorphism_effect()

        # 标题
        title_label = QLabel("更改付费区访问密码")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setWordWrap(False)
        title_label.setStyleSheet("""
            QLabel {
                color: rgba(255, 255, 255, 0.95);
                font-size: 20px;
                font-weight: bold;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
                margin: 8px 0px 25px 0px;
                padding: 0px 10px;
            }
        """)
        self.main_layout.addWidget(title_label)
        
        # 表单区域 - 使用网格布局确保标签和输入框正确对齐
        form_widget = QWidget()
        form_widget.setStyleSheet("QWidget { background: transparent; border: none; }")
        form_layout = QGridLayout(form_widget)
        form_layout.setVerticalSpacing(18)
        form_layout.setHorizontalSpacing(15)
        form_layout.setContentsMargins(0, 0, 0, 0)

        # 设置列宽比例：标签列固定宽度，输入框列自适应
        form_layout.setColumnMinimumWidth(0, 110)
        form_layout.setColumnStretch(0, 0)
        form_layout.setColumnStretch(1, 1)
        form_layout.setHorizontalSpacing(15)

        # 当前密码输入
        current_password_label = QLabel("当前密码:")
        current_password_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        current_password_label.setStyleSheet(self.get_label_style())
        form_layout.addWidget(current_password_label, 0, 0)

        self.current_password_input = QLineEdit()
        self.current_password_input.setEchoMode(QLineEdit.Password)
        self.current_password_input.setPlaceholderText("请输入当前密码")
        self.current_password_input.setStyleSheet(self.get_input_style())
        form_layout.addWidget(self.current_password_input, 0, 1)

        # 新密码输入
        new_password_label = QLabel("新密码:")
        new_password_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        new_password_label.setStyleSheet(self.get_label_style())
        form_layout.addWidget(new_password_label, 1, 0)

        self.new_password_input = QLineEdit()
        self.new_password_input.setEchoMode(QLineEdit.Password)
        self.new_password_input.setPlaceholderText("请输入新密码（建议6位以上）")
        self.new_password_input.setStyleSheet(self.get_input_style())
        form_layout.addWidget(self.new_password_input, 1, 1)

        # 确认新密码输入
        confirm_password_label = QLabel("确认新密码:")
        confirm_password_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        confirm_password_label.setStyleSheet(self.get_label_style())
        form_layout.addWidget(confirm_password_label, 2, 0)

        self.confirm_password_input = QLineEdit()
        self.confirm_password_input.setEchoMode(QLineEdit.Password)
        self.confirm_password_input.setPlaceholderText("请再次输入新密码")
        self.confirm_password_input.setStyleSheet(self.get_input_style())
        form_layout.addWidget(self.confirm_password_input, 2, 1)

        self.main_layout.addWidget(form_widget)
        
        # 添加弹性空间
        self.main_layout.addStretch()

        # 按钮容器
        button_container = QWidget()
        button_container.setStyleSheet("QWidget { background: transparent; border: none; }")
        button_layout = QHBoxLayout(button_container)
        button_layout.setSpacing(15)
        button_layout.setContentsMargins(0, 15, 0, 0)

        # 添加弹性空间使按钮居中
        button_layout.addStretch()

        # 清空按钮
        clear_btn = QPushButton("清空输入")
        clear_btn.setMinimumSize(120, 45)
        clear_btn.setStyleSheet(self.get_clear_button_style())
        clear_btn.clicked.connect(self.clear_inputs)
        button_layout.addWidget(clear_btn)

        # 取消按钮
        cancel_btn = QPushButton("取消")
        cancel_btn.setMinimumSize(120, 45)
        cancel_btn.setStyleSheet(self.get_cancel_button_style())
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)

        # 确认按钮
        confirm_btn = QPushButton("确认更改")
        confirm_btn.setMinimumSize(120, 45)
        confirm_btn.setStyleSheet(self.get_confirm_button_style())
        confirm_btn.clicked.connect(self.confirm_change)
        button_layout.addWidget(confirm_btn)

        # 添加弹性空间使按钮居中
        button_layout.addStretch()

        self.main_layout.addWidget(button_container)

        # 设置焦点和回车键绑定
        self.current_password_input.setFocus()

        # 绑定回车键
        self.current_password_input.returnPressed.connect(self.new_password_input.setFocus)
        self.new_password_input.returnPressed.connect(self.confirm_password_input.setFocus)
        self.confirm_password_input.returnPressed.connect(self.confirm_change)

        # 输入时立即重绘，避免只有切换焦点后才出现的显示延迟
        for _field in (self.current_password_input, self.new_password_input, self.confirm_password_input):
            _field.textEdited.connect(_field.update)

    def apply_glassmorphism_effect(self):
        """应用毛玻璃效果 - 粉色主题"""
        # 创建一个容器widget来承载内容，避免主窗口样式影响
        container = QWidget(self)
        container.setGeometry(0, 0, self.width(), self.height())

        # 设置容器的毛玻璃样式 - 粉色主题，增强透明度
        container.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 182, 193, 0.8),
                    stop:0.3 rgba(255, 192, 203, 0.75),
                    stop:0.7 rgba(255, 160, 180, 0.72),
                    stop:1 rgba(255, 175, 190, 0.78));
                border: 2px solid rgba(255, 182, 193, 0.6);
                border-radius: 25px;
            }
        """)

        # 将主布局设置到容器上
        if hasattr(self, 'main_layout'):
            container.setLayout(self.main_layout)

    def get_label_style(self):
        """获取标签样式"""
        return """
            QLabel {
                color: rgba(255, 255, 255, 0.9);
                font-size: 13px;
                font-weight: normal;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
                margin: 8px 5px 8px 0px;
                min-width: 80px;
                max-width: 120px;
            }
        """

    def get_input_style(self):
        """获取输入框样式"""
        return """
            QLineEdit {
                padding: 12px 15px;
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 10px;
                font-size: 14px;
                background-color: rgba(255, 255, 255, 0.15);
                color: rgba(255, 255, 255, 0.95);
                selection-background-color: rgba(255, 182, 193, 0.5);
                selection-color: #ffffff;
                min-height: 22px;
                margin: 8px 0px 8px 0px;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QLineEdit:focus {
                border-color: rgba(255, 182, 193, 0.8);
                background-color: rgba(255, 255, 255, 0.2);
                color: #ffffff;
            }
            QLineEdit:hover {
                border-color: rgba(255, 255, 255, 0.4);
            }
            QLineEdit::placeholder {
                color: rgba(255, 255, 255, 0.6);
            }
        """

    def get_cancel_button_style(self):
        """获取取消按钮样式"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 255, 255, 0.3),
                    stop:1 rgba(255, 255, 255, 0.2));
                color: rgba(255, 255, 255, 0.9);
                border: 1px solid rgba(255, 255, 255, 0.4);
                border-radius: 12px;
                font-size: 14px;
                font-weight: bold;
                font-family: 'Microsoft YaHei UI', sans-serif;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 255, 255, 0.4),
                    stop:1 rgba(255, 255, 255, 0.3));
                border-color: rgba(255, 255, 255, 0.6);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 255, 255, 0.2),
                    stop:1 rgba(255, 255, 255, 0.1));
            }
        """

    def get_confirm_button_style(self):
        """获取确认按钮样式"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(100, 149, 237, 0.8),
                    stop:1 rgba(65, 105, 225, 0.8));
                color: white;
                border: 1px solid rgba(100, 149, 237, 0.6);
                border-radius: 12px;
                font-size: 14px;
                font-weight: bold;
                font-family: 'Microsoft YaHei UI', sans-serif;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(100, 149, 237, 0.9),
                    stop:1 rgba(65, 105, 225, 0.9));
                border-color: rgba(100, 149, 237, 0.8);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(100, 149, 237, 0.7),
                    stop:1 rgba(65, 105, 225, 0.7));
            }
        """

    def get_clear_button_style(self):
        """获取清空按钮样式"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 193, 0.8),
                    stop:1 rgba(255, 175, 190, 0.8));
                color: white;
                border: 1px solid rgba(255, 107, 193, 0.6);
                border-radius: 12px;
                font-size: 14px;
                font-weight: bold;
                font-family: 'Microsoft YaHei UI', sans-serif;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 107, 193, 0.9),
                    stop:1 rgba(255, 175, 190, 0.9));
                border-color: rgba(255, 107, 193, 0.8);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 87, 173, 0.9),
                    stop:1 rgba(255, 155, 170, 0.9));
            }
        """

        # 根据内容固定对话框尺寸，避免首次显示布局错乱
        layout.setSizeConstraint(QLayout.SetFixedSize)

    def apply_final_layout(self):
        """应用最终布局，确保间距正确显示"""
        # 强制重新计算布局
        self.updateGeometry()

        # 强制重绘所有子控件
        for widget in self.findChildren(QWidget):
            widget.updateGeometry()
            widget.update()

        # 激活布局
        if self.layout():
            self.layout().invalidate()
            self.layout().activate()

        # 最后更新整个对话框
        self.update()
        self.repaint()

    def showEvent(self, event):
        """首帧显示时强制样式与布局生效，并按布局建议尺寸固定窗口"""
        super().showEvent(event)
        self.setUpdatesEnabled(False)
        try:
            # 触发样式 polish
            self.ensurePolished()
            for w in self.findChildren(QWidget):
                w.ensurePolished()
            # 激活并计算布局
            lay = self.layout()
            if lay:
                lay.invalidate()
                lay.activate()
            # 根据内容调整并固定尺寸（只在首次显示时）
            self.adjustSize()
            self.setFixedSize(self.size())
        finally:
            self.setUpdatesEnabled(True)
            self.update()
            self.repaint()

    def confirm_change(self):
        """确认更改密码"""
        print("🔍 密码修改按钮被点击")
        current_password = self.current_password_input.text().strip()
        new_password = self.new_password_input.text().strip()
        confirm_password = self.confirm_password_input.text().strip()
        
        print(f"🔍 输入信息: 当前密码长度={len(current_password)}, 新密码长度={len(new_password)}, 确认密码长度={len(confirm_password)}")
        
        # 验证输入
        if not current_password:
            self.show_message("警告", "请输入当前密码！", "warning")
            self.current_password_input.setFocus()
            return

        if not new_password:
            self.show_message("警告", "请输入新密码！", "warning")
            self.new_password_input.setFocus()
            return

        if len(new_password) < 4:
            self.show_message("警告", "新密码长度至少4位！", "warning")
            self.new_password_input.setFocus()
            return

        if new_password != confirm_password:
            self.show_message("警告", "两次输入的新密码不一致！", "warning")
            self.confirm_password_input.setFocus()
            return

        if current_password == new_password:
            self.show_message("警告", "新密码不能与当前密码相同！", "warning")
            self.new_password_input.setFocus()
            return

        try:
            print("🔍 检查父窗口和密码修改方法")
            if self.parent():
                print(f"✅ 父窗口存在: {type(self.parent())}")
                if hasattr(self.parent(), 'change_premium_password'):
                    print("✅ 父窗口有 change_premium_password 方法")
                    success = self.parent().change_premium_password(current_password, new_password)
                    print(f"🔍 密码修改结果: {success}")
                    if success:
                        print("✅ 密码修改成功，开始清理和显示提示")
                        # 清空输入框
                        self.current_password_input.clear()
                        self.new_password_input.clear()
                        self.confirm_password_input.clear()
                        print("✅ 输入框已清空")
                        # 直接显示成功消息
                        print("🔍 准备显示成功消息")
                        self.show_success_message()
                        print("✅ 成功消息显示完成")
                    else:
                        print("🔍 显示失败消息")
                        self.show_message("错误", "密码更改失败！\n请检查当前密码是否正确。", "error")
                        self.current_password_input.setFocus()
                        self.current_password_input.selectAll()
                else:
                    print("❌ 父窗口没有 change_premium_password 方法")
                    self.show_message("错误", "无法访问密码更改功能！", "error")
            else:
                print("❌ 父窗口不存在")
                self.show_message("错误", "无法访问密码更改功能！", "error")
        except Exception as e:
            print(f"❌ 密码修改异常: {e}")
            import traceback
            traceback.print_exc()
            self.show_message("错误", f"密码更改过程中出现错误：\n{str(e)}", "error")
    
    def show_success_message(self):
        """显示密码修改成功消息"""
        print("🔍 开始显示成功消息")
        try:
            # 使用标准消息框确保显示
            from PySide2.QtWidgets import QMessageBox
            print("🔍 创建消息框")
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle("密码修改成功")
            msg_box.setText("✅ 密码更改成功！\n新密码已安全存储，下次访问时生效。")
            msg_box.setIcon(QMessageBox.Information)
            msg_box.setStandardButtons(QMessageBox.Ok)
            print("🔍 显示标准成功消息框")
            result = msg_box.exec_()
            print(f"✅ 成功消息显示完成，用户点击了: {result}")
            # 用户关闭消息框后，关闭密码设置对话框
            print("🔍 准备关闭密码设置对话框")
            self.accept()
            print("✅ 密码设置对话框已关闭")
        except Exception as e:
            print(f"❌ 显示成功消息失败: {e}")
            import traceback
            traceback.print_exc()

    def show_message(self, title: str, message: str, msg_type: str = "info"):
        """显示自定义样式的消息框"""
        print(f"🔍 显示消息: {title} - {message} - {msg_type}")
        # 直接导入并使用CustomMessageBox
        try:
            # 使用统一的毛玻璃消息框
            from custom_message_box import information, warning, critical, success
            print(f"✅ 成功导入消息框模块")
            if msg_type == "error":
                print(f"🔍 显示错误消息")
                critical(self, title, message)
            elif msg_type == "warning":
                print(f"🔍 显示警告消息")
                warning(self, title, message)
            elif msg_type == "success":
                print(f"🔍 显示成功消息")
                success(self, title, message)
            else:
                print(f"🔍 显示信息消息")
                information(self, title, message)
            print(f"✅ 消息显示完成")
        except ImportError as e:
            print(f"❌ 导入消息框模块失败: {e}")
            # 如果导入失败，使用标准消息框
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle(title)
            msg_box.setText(message)
            msg_box.exec_()
        except Exception as e:
            print(f"❌ 显示消息失败: {e}")
            import traceback
            traceback.print_exc()

    def clear_inputs(self):
        """清空所有输入框"""
        self.current_password_input.clear()
        self.new_password_input.clear()
        self.confirm_password_input.clear()
        # 将焦点设置到第一个输入框
        self.current_password_input.setFocus()
        # 显示提示信息
        self.show_message("提示", "已清空所有输入框", "info")

    def get_passwords(self):
        """获取输入的密码（用于外部调用）"""
        return {
            'current': self.current_password_input.text().strip(),
            'new': self.new_password_input.text().strip(),
            'confirm': self.confirm_password_input.text().strip()
        }
